(define (rle s)
	(define (helper val prev s)
		(if (null? s)
			(cons-stream (list prev val) nil)
			(if (null? (cdr-stream s))
				(if (= prev (car s))
					(cons-stream (list prev (+ val 1)) nil)
					(cons-stream (list prev val) (cons-stream (list (car s) 1) nil))
				)
				(if (= prev (car s))
					(helper (+ val 1) prev (cdr-stream s))
					(cons-stream (list prev val) (helper 1 (car s) (cdr-stream s)))
				)
			)
		)
	)
	(if (null? s)
		nil
    	(helper 1 (car s) (cdr-stream s))
	)
)

(define (group-by-nondecreasing s)
	(define (helper chain prev s)
		(if (null? s)
			(cons-stream chain nil)
			(if (null? (cdr-stream s))
				(if (< (car s) prev)
					(cons-stream chain (cons-stream (list (car s)) nil))
					(cons-stream (append chain (list (car s))) nil)
				)
				(if (< (car s) prev)
					(cons-stream chain (helper (list (car s)) (car s) (cdr-stream s)))
					(helper (append chain (list (car s))) (car s) (cdr-stream s))
				)
			)
		)
	)
	(if (null? s)
		nil
		(helper (list (car s)) (car s) (cdr-stream s))
	)
)


(define finite-test-stream
    (cons-stream 1
        (cons-stream 2
            (cons-stream 3
                (cons-stream 1
                    (cons-stream 2
                        (cons-stream 2
                            (cons-stream 1 nil))))))))

(define infinite-test-stream
    (cons-stream 1
        (cons-stream 2
            (cons-stream 2
                infinite-test-stream))))

